package com.suneast.suneaststore.modules.personal.order.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.order.ExpressCompanyBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.order.OrderHandler;
import com.suneast.suneaststore.modules.personal.order.event.ConfirmDeliverGoodsResult;
import com.suneast.suneaststore.modules.personal.order.event.DeliverConfirmedSucceed;
import com.suneast.suneaststore.modules.personal.order.event.ExpressListResult;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ConfirmDeliveredFragment extends BaseFragment {
    @Override
    public int setLayout() {
        return R.layout.fragment_confirm_delivered;
    }

    private int pos = -1;
    private int orderId = -1;

    public ConfirmDeliveredFragment withPos(int pos) {
        this.pos = pos;
        return this;
    }

    public ConfirmDeliveredFragment withOrderId(int orderId) {
        this.orderId = orderId;
        return this;
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.edit_choose_company)
    EditText chooseCompanyEt;
    @BindView(R.id.edit_express_number)
    EditText expressNumberEt;
    @BindView(R.id.btn_confirm)
    Button conFirmBtn;

    private List<ExpressCompanyBean> mCompanyBeanList;
    private ExpressCompanyBean curCompanyBean = null;

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        expressNumberEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                conFirmBtn.setEnabled(s.length() > 0);
            }
        });
        mCompanyBeanList = new ArrayList<>();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
        OrderHandler.requestExpressCompanyList();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotCompanyListResult(ExpressListResult result) {
        if (result.getValue() == Flag.Result.SUCCEED) {
            mCompanyBeanList.addAll(result.getCompanyBeanList());
        }
    }

    private AlertDialog companyListDialog = null;

    private void showCompanyListDialog() {
        if (companyListDialog == null) {
            String[] companyArray = getCompanyArray(mCompanyBeanList);
            if (companyArray != null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(_mActivity);
                builder.setTitle("选择快递公司");
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setSingleChoiceItems(companyArray, 0,
                        (DialogInterface dialog, int which) -> {
                            curCompanyBean = mCompanyBeanList.get(which);
                            chooseCompanyEt.setText(curCompanyBean.getName());
                            dialog.dismiss();
                        });
                companyListDialog = builder.create();
                companyListDialog.setCancelable(true);
            }
        }
        if (companyListDialog != null) {
            companyListDialog.show();
        }
    }

    private String[] getCompanyArray(List<ExpressCompanyBean> list) {
        if (list != null && list.size() > 0) {
            String[] array = new String[list.size()];
            for (int i = 0, iLength = list.size(); i < iLength; i++) {
                array[i] = list.get(i).getName();
            }
            return array;
        }
        return null;
    }

    @OnClick({R.id.btn_confirm, R.id.edit_choose_company})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm: {
                if (curCompanyBean != null) {
                    String ssnNoStr = expressNumberEt.getText().toString();
                    Log.d(TAG, "onViewClick: orderId = " + orderId + " name = " + curCompanyBean.getName() +
                            " express = " + curCompanyBean.getExpress() + "ssnNoStr = " + ssnNoStr);
                    if (ssnNoStr.length() > 0) {
                        OrderHandler.confirmDeliverGoods(pos, orderId, curCompanyBean.getName(),
                                curCompanyBean.getExpress(), ssnNoStr);
                    } else if ("帘邦配送".equals(curCompanyBean.getName())) {

                        OrderHandler.confirmDeliverGoods(pos, orderId, curCompanyBean.getName(),
                                curCompanyBean.getExpress(), ssnNoStr);
                    } else {
                        Toast.makeText(_mActivity, "请填写物流单号", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(_mActivity, "请填写物流公司名称", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.edit_choose_company: {
                showCompanyListDialog();
            }
            break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConfirmDeliveredResult(ConfirmDeliverGoodsResult result) {
        if (result.getValue() == Flag.Result.SUCCEED) {
            EventBus.getDefault().post(new DeliverConfirmedSucceed(result.getPos()));
            Toast.makeText(_mActivity, "确认发货成功", Toast.LENGTH_SHORT).show();
            pop();
        } else {
            Toast.makeText(_mActivity, "确认发货失败", Toast.LENGTH_SHORT).show();
        }
    }
}
